package cn.worldyao.demo.service.impl;

import cn.worldyao.demo.entity.SysPermissionRoleItem;
import cn.worldyao.demo.entity.SysRole;
import cn.worldyao.demo.mapper.SysPermissionRoleMapper;
import cn.worldyao.demo.mapper.SysRoleMapper;
import cn.worldyao.demo.service.SysRoleService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yaozi
 * @since 2020-03-11
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    public SqlSessionFactory factory;

    @Override
    public boolean updatePermission(SysPermissionRoleItem sysPermissionRoleItem) {
        SysRole sysRole = sysPermissionRoleItem.getSysRole();
        String permissionPath = StringUtils.join(sysPermissionRoleItem.getPermissions(), ",");
        UpdateWrapper<SysRole> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("RID", sysRole.getRid());
        // 设置权限
        sysRole.setPremissPath(permissionPath);
        // 更新时间
        sysRole.setUpdateTime(LocalDateTime.now());
        return this.update(sysRole, updateWrapper);
    }

    @Override
    public boolean save(SysPermissionRoleItem sysPermissionRoleItem) {
        SysRole sysRole = sysPermissionRoleItem.getSysRole();
        sysRole.Init();
        String permissionPath = StringUtils.join(sysPermissionRoleItem.getPermissions(), ",");
        sysRole.setPremissPath(permissionPath);
        System.out.println(sysRole);
        return this.save(sysRole);
    }

    @Override
    public List<SysRole> listRoles() {
        SqlSession sqlSession = factory.openSession();
        List<SysRole> s = sqlSession.getMapper(SysRoleMapper.class).listRoles();
        sqlSession.close();
        return s;
    }
}
